<template>
  <div id='CalcFormulaForm'>
    <!-- tab基本信息表单  -->
    <el-scrollbar style='height: 100%'>
      <el-button type='primary' @click='saveForm' class='saveBtn'>保存</el-button>
      <el-form ref='formRef' :model='formData' label-width='110px' class='form-input-m' inline-message>
        <el-row :gutter='20'>
          <el-col :span='12'>
            <el-form-item label='核算表单' prop='itemId'>
              <el-select v-model='formData.itemId' placeholder='请选择核算表单' @change='changeItem' style='width: 200px;'>
                <el-option v-for='item in calcItemList' :key='item.id' :label='item.itemName' :value='item.id' />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='是否启用' prop='isEnable'>
              <el-switch v-model='formData.isEnable' inline-prompt active-text='是' inactive-text='否' :active-value=1 :inactive-value=0></el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='12'>
            <el-form-item label='编码' prop='code'>
              <el-input v-model='formData.code' placeholder='请输入编码' clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='名称' prop='name'>
              <el-input v-model='formData.name' placeholder='请输入名称' clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='12'>
            <el-form-item label='计算模式' prop='calcMode'>
              <el-select v-model='formData.calcMode' placeholder='请选择计算模式' style='width: 200px;'>
                <el-option v-for='item in calcModeList' :key='item.code' :label='item.name' :value='item.code' />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span='12'>
            <el-form-item label='结果类型' prop='resultType'>
              <el-select v-model='formData.resultType' placeholder='请选择结果类型' style='width: 200px;'>
                <el-option v-for='item in resultTypeList' :key='item.code' :label='item.name' :value='item.code' />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20' v-if="formData.calcMode==='reduce'">
          <el-col :span='20'>
            <el-form-item label='扣减总分' prop='reduceSum'>
              <vxe-input v-model='formData.reduceSum' type='number' placeholder='扣减总分' transfer></vxe-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-col :span='12'>
            <el-form-item label='有效期【起】' prop='startDateStr'>
              <vxe-input v-model='formData.startDateStr' type='date' placeholder='有效期【起】' transfer @change='changeStart'></vxe-input>
            </el-form-item>
          </el-col>

          <el-col :span='12'>
            <el-form-item label='有效期【止】' prop='endDateStr'>
              <vxe-input v-model='formData.endDateStr' type='date' placeholder='有效期【止】' transfer @change='changeEnd'></vxe-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter='20'>
          <el-form-item label='备注描述' prop='remarks'>
            <el-input
              v-model='formData.remarks'
              placeholder='备注描述'
              style='width: 600px'
              class='remarkDescriptions'
              :rows='3'
              type='textarea'
            />
          </el-form-item>
        </el-row>
      </el-form>

      <!-- 配置扩展属性弹框 -->
      <EditExtraProperties ref='EditExtraPropertiesRef' />
      <el-divider>
        <el-button type='primary' @click='resetFormula'>重置公式</el-button>
      </el-divider>


      <Splitpanes
        :style="{height: useSize === 'small' ? 'calc(100% - 24px - 20px - 210px - 48px - 2px)' : useSize === 'default' ? 'calc(100% - 32px - 20px - 251px - 48px)' : 'calc(100% - 40px - 20px - 343px - 48px)'}"
        class='restSplitPanes'>
        <Pane size='30'>
          <vxe-table ref='dictTable' border='inner' align='center' height='auto'
                     :data='calcElementList'
                     :expand-config='{ expandAll: true, reserve: true }'
                     @current-change='dictRowClick'
                     :row-config='{ isCurrent: true, isHover: true }'
                     :column-config='{ resizable: true }'
                     :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                     resizable show-overflow keep-source>
            <vxe-column field='elementName' title='核算要素'></vxe-column>
          </vxe-table>
        </Pane>

        <Pane size='50'>
          <vxe-textarea v-model='formData.formulaTitle' :autosize='{ minRows: 12 }' placeholder='计算公式' class='calcTextArea' @click='handleInputBlur($event)' resize='vertical'></vxe-textarea>
        </Pane>
        <Pane size='20'>

          <vxe-table ref='dictTable' border='inner' align='center' height='auto'
                     :data='operatorList'
                     :expand-config='{ expandAll: true, reserve: true }'
                     @current-change='dictRowClick2'
                     :row-config='{ isCurrent: true, isHover: true }'
                     :column-config='{ resizable: true }'
                     :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                     resizable show-overflow keep-source>
            <vxe-column field='operator' title='运算'></vxe-column>
          </vxe-table>
        </Pane>
      </Splitpanes>
    </el-scrollbar>
  </div>

</template>


<script lang='ts' setup>
// 引入组件区==========
import { getCurrentInstance, reactive, ref } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import EditExtraProperties from '@/components/EditExtraProperties.vue';
import { Pane, Splitpanes } from 'splitpanes';
import { IsEmpty } from '@/utils/common';

// 方法定义区 =============
defineExpose({ initPage, clearFormData, initAddPage, addNew });

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();

// 基本信息form表单
let formData = reactive({
  id: '',
  code: '' /*编码*/,
  name: '' /*名称*/,
  itemId: '',
  itemName: '',
  calcMode: '',
  resultType: '',
  reduceSum: 0,
  isEnable: 1,
  startDate: null,
  endDate: null,
  startDateStr: '',
  endDateStr: '',
  remarks: null,
  formula: '',
  formulaTitle: ''
});


let formRef = ref(null); //form表单标记ref
let showLoading = ref(false); //保存按钮
let repSeq = 0;


function initAddPage(addSeq: number) {
  repSeq = addSeq;
  findCalcItemList();
  getCalcElementList();
  getCalcModeList();
  getResultTypeList();
}

let calcItemList: any = reactive([]);
let calcElementList: any = reactive([]);
let calcModeList: any = reactive([]);

let operatorList: any = ref([
  { operator: '+' },
  { operator: '-' },
  { operator: '*' },
  { operator: '/' },
  { operator: '(' },
  { operator: ')' }
]);
let resultTypeList: any = reactive([]);

let useSize = ref(localStorage.getItem('uiSize') || 'small');//监听页面尺寸变化

/**
 * 获取核算表单
 */
function findCalcItemList() {
  calcItemList.length = 0;
  proxy.$http.get('/wk/calc/item/getCalcItemList').then((res: any) => {
    calcItemList.push(...res.data);
  }).catch((err: any) => {
    proxy.$alert(err, '提示');
  });
}

/**
 * 获取核算要素
 */
function getCalcElementList() {
  calcElementList.length = 0;
  proxy.$http.get('/wk/calc/element/getCalcElementList').then((res: any) => {
    calcElementList.push(...res.data);
  }).catch((err: any) => {
    proxy.$alert(err, '提示');
  });
}

/**
 * 获取计算模式
 */
async function getCalcModeList() {
  calcModeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: 'calcMode' } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'calcMode');
  calcModeList.push(...horizontalType.detailDataList);
}

/**
 * 结果类型
 */
async function getResultTypeList() {
  resultTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: 'resultType' } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'resultType');
  resultTypeList.push(...horizontalType.detailDataList);
}

function addNew() {
  clearFormData(); // 清空表单
}

/**
 * 左侧表格点击当前行传过来的数据
 * @param row
 */
function initPage(row: any) {
  if (row !== null) {
    for (let prop in row) {
      formData[prop] = row[prop];
    }
  }
}


/**
 * 清空数据
 */
function clearFormData() {
  for (let key in formData) {
    formData[key] = '';
  }
  const el: any = proxy.$refs['formRef'];
  el.resetFields(); //重置该表单项，将其值重置为初始值，并移除校验结果
}

/**
 * 点击要素
 * @param row
 * @param rowIndex
 */
function dictRowClick({ row }: any) {
  if (formData.formulaTitle === undefined || formData.formulaTitle === null) {
    formData.formulaTitle = '';
  }
  if (formData.formula === undefined || formData.formula === null) {
    formData.formula = '';
  }
  let elementName = row.elementName;
  let pageColumnStr = formData.formulaTitle;
  let resultPageColumnStr = '';
  if (pageColumnStr.length <= cursorIndex.value) {
    resultPageColumnStr = pageColumnStr + '#' + elementName + '#';
  } else {
    resultPageColumnStr = pageColumnStr.substring(0, cursorIndex.value) + '#' + elementName + '#' + pageColumnStr.substring(cursorIndex.value, pageColumnStr.length);
  }
  formData.formulaTitle = resultPageColumnStr;
}

/**
 * 点击运算符
 * @param row
 */
function dictRowClick2({ row }: any) {
  let operator = row.operator;
  let pageColumnStr = formData.formulaTitle;
  let resultPageColumnStr = '';
  if (pageColumnStr.length <= cursorIndex.value) {
    resultPageColumnStr = pageColumnStr + operator;
  } else {
    resultPageColumnStr = pageColumnStr.substring(0, cursorIndex.value) + operator + pageColumnStr.substring(cursorIndex.value, pageColumnStr.length);
  }
  formData.formulaTitle = resultPageColumnStr;
}

function changeStart() {
  formData.startDate = formData.startDateStr;
}

function changeEnd() {
  formData.endDate = formData.endDateStr;
}

function changeItem(itemId: any) {
  formData.itemName = calcItemList.filter(item => item.id === itemId)[0].itemName;
}

function resetFormula() {
  formData.formulaTitle = '';
  formData.formula = '';
}


let cursorIndex = ref(0);

/**
 * 鼠标点击事件
 * @param e
 */
function handleInputBlur(e) {
  cursorIndex.value = e.$event.srcElement.selectionStart;
}


const regex = /#(.*?)#/g;

function replaceMatch(match: string, group1: string): string {
  let element = calcElementList.filter(item => item.elementName === group1)[0];
  if (element === null || element === undefined) {
    VxeMessage('核算公式异常', VxeNotifyType.error);
  }
  return '#' + element.id + '#';
}

/**
 * 保存按钮
 */
function saveForm() {
  let url = '';
  // 判断添加和编辑接口
  let isAdd = true;
  if (IsEmpty(formData.id)) {
    url = '/wk/calc/formula/add';
  } else {
    isAdd = false;
    url = '/wk/calc/formula/update';
  }

  formData.formula = formData.formulaTitle.replace(regex, replaceMatch);
  formData.startDateStr = formData.startDate;
  formData.endDateStr = formData.endDate;
  formData.startDate = null;
  formData.endDate = null;

  proxy.$http.post(url, formData).then((res: any) => {
    if (res.status.code === 1) {
      if (isAdd) {
        VxeMessage('新增核算公式成功', VxeNotifyType.success);
      } else {
        VxeMessage('修改核算公式成功', VxeNotifyType.success);
      }
      proxy.$emit('getTableData'); //触发父组件重新获取表格数据
    } else {
      if (isAdd) {
        VxeMessage('新增核算公式失败', VxeNotifyType.error);
      } else {
        VxeMessage('修改核算公式失败', VxeNotifyType.error);
      }
      proxy.$emit('getTableData'); //触发父组件重新获取表格数据
      return;
    }
  }).catch((err: any) => {
    VxeMessage('新增核算公式异常', VxeNotifyType.error);
  });

  showLoading.value = false;
  clearFormData(); //清空数据
}

</script>

<style lang='scss' scoped>
#CalcFormulaForm {
  padding: 0;
  height: 100%;

  :deep(.el-scrollbar__view) {
    height: 100%;
    //右侧基本信息 保存按钮
    .saveBtn {
      margin: 10px 0 10px 20px;
    }

    .el-form {
      padding: 0 10px;
    }

    .el-row {
      margin-left: 0 !important;
      margin-right: 0 !important;
      // 基本信息表单 备注描述
      .remarkDescriptions {
        width: 600px;
        margin-left: 10px;
      }
    }

    .calcTextArea {
      width: calc(100% - 2px);
    }
  }
}
</style>

